package com.example.test.启动线程.生成消费lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Data {

    private Lock lock = new ReentrantLock();

    private Condition proCondition = lock.newCondition();

    private Condition conCondition = lock.newCondition();

    private String message;

    public String getMessage() throws InterruptedException {

        lock.lock();
        try {
            while (message == null) {
                conCondition.await();
            }
            proCondition.signalAll();
            System.out.println("消费者:" + message);
            return message;
        } finally {
            message = null;
            lock.unlock();
        }
    }

    public void setMessage(String message) {
        lock.lock();
        try {
            while (this.message != null) {
                proCondition.await();
            }
            System.out.println("生产者:" + message);
            this.message = message;
            conCondition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
